package org.urchr.beorganized.api.impl.file;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.coyote.http11.filters.BufferedInputFilter;
import org.urchr.beorganized.api.base.BaseAPIServlet;
import org.urchr.beorganized.dao.NotesDAO;
import org.urchr.beorganized.dao.errors.GeneralException;
import org.urchr.beorganized.dao.tables.Note;

public class Download extends BaseAPIServlet {

	public Download() {
		skipBody = true;
	}
	
	private void transformImage(InputStream inputStream, int width, String contentType, HttpServletResponse res) throws IOException{
		BufferedImage image = ImageIO.read(inputStream);
		if(image.getWidth()<=width){
			res.setContentType(contentType);
			res.setContentType("image/jpeg");
			ImageIO.write(image, "jpg", res.getOutputStream());
			return;
		}
		AffineTransform tx = new AffineTransform();
		tx.scale((float)width/(float)image.getWidth(), (float)width/(float)image.getWidth());
		AffineTransformOp op = new AffineTransformOp (tx,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
		image = op.filter(image, null);
		res.setContentType("image/jpeg");
		ImageIO.write(image, "jpg", res.getOutputStream());
	}
	
	@Override
	protected void doProcess() throws GeneralException {
		String shareCode = request.getParameter("sharecode");
		int width = NotesDAO.safeInt(request.getParameter("width"), 0);
		Note note = NotesDAO.getNoteByCode(shareCode, false);
		if(note!=null){
			try {
				InputStream stream = null;
				File file = new File(servletContext.getRealPath(
						NotesDAO.FILES_STORE+note.getShareCode()+".bin"));
				if(file.exists()){
//					System.out.println("File exists - from disk");
					stream = new BufferedInputStream(new FileInputStream(file));
				}else{
//					System.out.println("File not found - from DB");
					if(note.getData()==null){
						response.setStatus(HttpServletResponse.SC_NOT_FOUND);
//						System.out.println("Error - no data");
						return;
					}
					stream = new ByteArrayInputStream(note.getData());
				}
				if(width>0){
					transformImage(stream, width, note.getContentType(), response);
					return;
				}
				
				response.setContentType(note.getContentType());
				if(note.getType()!=Note.TYPE_IMAGE){
					String fileName = note.getFileName();
					if(null==fileName || "".equals(fileName))
						fileName = note.getId()+".txt";
					response.addHeader("Content-Disposition", "attachment; filename="+fileName);					
				}
				BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
				for (int d = stream.read(); d!=-1; d = stream.read()) {
					outputStream.write(d);
				}
				outputStream.flush();
				outputStream.close();
				return;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		response.setStatus(HttpServletResponse.SC_NOT_FOUND);
	}

}
